import { observable } from "mobx";
import { observer } from "mobx-react";

import { message, Icon } from "antd";
import "./css/ImgUpload.less";

@observer
export default class ImgUpload extends React.Component {
    @observable imgDataUrl = "";

    componentWillMount() {
        this.imgDataUrl = this.props.defaultImg;
    }

    onFileChange(e) {
        const that = this;
        const target = e.nativeEvent.target;
        const { onChange } = this.props;
        const file = target.files[0];

        if(!file || !~file.type.indexOf("image")) {
            target.value="";
            that.imgDataUrl = "";
            onChange("");
            file && message.error("请选择正确的图片格式");
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function() {
            that.imgDataUrl = this.result;
            onChange(this.result);
        }
        reader.readAsDataURL(file);
    }

    render() {
        return (
            <div className="mobilemode-img-upload">
                { this.imgDataUrl ?
                    <img src={this.imgDataUrl} />
                    : null
                }
                <input type="file" onChange={this.onFileChange.bind(this)} />
                <Icon type="plus" />
                <p>Upload</p>
            </div>
        );
    }
}